package com.mcptt.db.op;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;

import com.cloudptt.api.product.log.Log;
import com.mcptt.db.DBProvider;
import com.mcptt.db.DbConst;
import com.mcptt.db.model.ConfigFileInfo;

public class ConfigFileDbOperator {

    public static String THIS_FILE = "ConfigFileDbOperator";
    private Context ctx = null;

    public ConfigFileDbOperator(Context ctx)
    {
	this.ctx = ctx;
    }

    public ConfigFileInfo getConfigFileInfoByFileName(String fileName)
    {
    	Log.debug(this.getClass(), "getConfigFileInfoByFileName");
	ContentResolver cr = ctx.getContentResolver();
	String selection = DbConst.COL_FileName + "=?";
	ConfigFileInfo info = null;

	Cursor cursor = null;
	try 
	{
	    cursor = cr.query(DbConst.CONFIG_URI,
		    DBProvider.CONFIG_FULL_PROJECTION, selection,
		    new String[] { fileName }, DbConst.COL_FileName );

	    if(cursor !=null
		    && cursor.getCount() > 0)
	    {			
		if(cursor.moveToFirst())
		{
		    info = new ConfigFileInfo(cursor);
		}
	    }
	} 
	catch (Exception e) 
	{
	    // TODO: handle exception
	}
	finally
	{
	    if(cursor != null)
	    {
		cursor.close();
		cursor = null;
	    }
	}

	return info;
    }


    public void addConfigFileInfo(ConfigFileInfo info)
    {
	String fileName = info.getFileName();
	ContentResolver cr = ctx.getContentResolver();
	String selection = DbConst.COL_FileName + "=?";	

	Cursor cursor = null;
	try 
	{
	    cursor = cr.query(DbConst.CONFIG_URI,
		    DBProvider.CONFIG_FULL_PROJECTION, selection,
		    new String[] {fileName}, null);
	    if (cursor == null
		    || cursor.getCount() <= 0)
	    {
		cr.insert(DbConst.CONFIG_URI, info.getContentValues());
	    }
	} 
	catch (Exception e) 
	{
	    e.printStackTrace();
	    // TODO: handle exception
	}
	finally
	{
	    if(cursor != null)
	    {
		cursor.close();
		cursor = null;
	    }
	}
    }
    public void deleteAllConfigFileInfo()
    {
	ContentResolver cr = ctx.getContentResolver();
	cr.delete(DbConst.CONFIG_URI, null,null);
    }

    public void updateConfigFileInfo(ConfigFileInfo info)
    {
	String fileName = info.getFileName();
	ContentResolver cr = ctx.getContentResolver();
	String selection = DbConst.COL_FileName + "=?";
	int ret = cr.update(DbConst.CONFIG_URI, info.getContentValues(), selection, new String[] {fileName});
	if(ret <= 0)
	{
	    addConfigFileInfo(info);
	}
    }
}
